package com.xul.srb.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xul.srb.base.uitl.JwtUtils;
import com.xul.srb.core.enums.BorrowerStatusEnum;
import com.xul.srb.core.enums.IntegralEnum;
import com.xul.srb.core.mapper.BorrowerAttachMapper;
import com.xul.srb.core.mapper.BorrowerMapper;
import com.xul.srb.core.mapper.UserInfoMapper;
import com.xul.srb.core.mapper.UserIntegralMapper;
import com.xul.srb.core.pojo.entity.Borrower;
import com.xul.srb.core.pojo.entity.BorrowerAttach;
import com.xul.srb.core.pojo.entity.UserInfo;
import com.xul.srb.core.pojo.entity.UserIntegral;
import com.xul.srb.core.pojo.vo.BorrowerApprovalVO;
import com.xul.srb.core.pojo.vo.BorrowerAttachVO;
import com.xul.srb.core.pojo.vo.BorrowerDetailVO;
import com.xul.srb.core.pojo.vo.BorrowerVO;
import com.xul.srb.core.service.BorrowerAttachService;
import com.xul.srb.core.service.BorrowerService;
import com.xul.srb.core.service.DictService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 借款人 服务实现类
 * </p>
 *
 * @author xul
 * @since 2021-11-06
 */
@Service
public class BorrowerServiceImpl extends ServiceImpl<BorrowerMapper, Borrower> implements BorrowerService {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private BorrowerAttachMapper borrowerAttachMapper;

    @Resource
    private DictService dictService;

    @Resource
    private BorrowerAttachService borrowerAttachService;

    @Resource
    private UserIntegralMapper userIntegralMapper;


    /**
     * 保存借款人信息
     *
     * @param borrowerVO
     * @param request
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveByBorrowerVO(BorrowerVO borrowerVO, HttpServletRequest request) {
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);
        // 根据用户id获取到用户的信息
        UserInfo userInfo = userInfoMapper.selectById(userId);

        // 保存借款人的基本信息
        Borrower borrower = new Borrower();
        BeanUtils.copyProperties(borrowerVO, borrower);
        borrower.setUserId(userId);
        borrower.setName(userInfo.getName());
        borrower.setIdCard(userInfo.getIdCard());
        borrower.setMobile(userInfo.getMobile());
        // 认证中
        borrower.setStatus(BorrowerStatusEnum.AUTH_RUN.getStatus());
        baseMapper.insert(borrower);

        // 保存借款人的上传的图片信息
        List<BorrowerAttach> borrowerAttachList = borrowerVO.getBorrowerAttachList();
        borrowerAttachList.forEach(borrowerAttach -> {
            borrowerAttach.setBorrowerId(borrower.getId());
            borrowerAttachMapper.insert(borrowerAttach);
        });

        // 更新用户信息的状态 认证中
        userInfo.setBorrowAuthStatus(BorrowerStatusEnum.AUTH_RUN.getStatus());
        userInfoMapper.updateById(userInfo);

    }

    /**
     * 获取借款人认证状态
     *
     * @param request
     * @return
     */
    @Override
    public Integer getBorrowerStatus(HttpServletRequest request) {
        String token = request.getHeader("token");
        Long userId = JwtUtils.getUserId(token);
        QueryWrapper<Borrower> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        Borrower borrower = baseMapper.selectOne(wrapper);
        // 借款人尚未提交信息
        if (borrower.getStatus() == null) {
            return BorrowerStatusEnum.NO_AUTH.getStatus();
        }
        return borrower.getStatus();
    }

    /**
     * 获取借款人分页列表
     *
     * @param page
     * @param limit
     * @param keyword
     * @return
     */
    @Override
    public IPage<Borrower> listPage(Long page, Long limit, String keyword) {
        Page<Borrower> pageParam = new Page<>(page, limit);
        if (StringUtils.isEmpty(keyword)) {
            return baseMapper.selectPage(pageParam, null);
        }

        QueryWrapper<Borrower> wrapper = new QueryWrapper<>();
        //  wrapper.like("name", keyword).or().like("mobile", keyword).or().like("id_card", keyword).orderByDesc("id");
        wrapper.like("name", keyword)
                .or().like("id_card", keyword)
                .or().like("mobile", keyword)
                .orderByDesc("id");
        return baseMapper.selectPage(pageParam, wrapper);
    }

    /**
     * 获取借款人信息
     *
     * @param id
     * @return
     */
    @Override
    public BorrowerDetailVO getBorrowerDetailVOById(Long id) {
        BorrowerDetailVO borrowerDetailVO = new BorrowerDetailVO();
        Borrower borrower = baseMapper.selectById(id);
        if (borrower == null) {
            return new BorrowerDetailVO();
        }
        BeanUtils.copyProperties(borrower, borrowerDetailVO);

        borrowerDetailVO.setSex(borrower.getSex() == 1 ? "男" : "女");
        borrowerDetailVO.setMarry(borrower.getMarry() ? "是" : "否");

        // 计算下拉框选项
        borrowerDetailVO.setEducation(dictService.getNameByDictCodeAndValue(borrower.getEducation(), "education"));
        borrowerDetailVO.setIndustry(dictService.getNameByDictCodeAndValue(borrower.getIndustry(), "industry"));
        borrowerDetailVO.setIncome(dictService.getNameByDictCodeAndValue(borrower.getIncome(), "income"));
        borrowerDetailVO.setReturnSource(dictService.getNameByDictCodeAndValue(borrower.getReturnSource(), "returnSource"));
        borrowerDetailVO.setContactsRelation(dictService.getNameByDictCodeAndValue(borrower.getContactsRelation(), "relation"));

        // 审批状态
        borrowerDetailVO.setStatus(BorrowerStatusEnum.getMsgByStatus(borrower.getStatus()));

        // 获取附件vo的数据
        List<BorrowerAttachVO> borrowerAttachVOList = borrowerAttachService.getBorrowerAttachByBorrowerId(id);
        borrowerDetailVO.setBorrowerAttachVOList(borrowerAttachVOList);

        return borrowerDetailVO;
    }

    /**
     * 借款额度审批
     *
     * @param borrowerApprovalVO
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void approval(BorrowerApprovalVO borrowerApprovalVO) {
        // 根据借款人id获取到借款人信息 并修改借款人状态
        Long borrowerId = borrowerApprovalVO.getBorrowerId();
        Borrower borrower = baseMapper.selectById(borrowerId);
        borrower.setStatus(borrowerApprovalVO.getStatus());
        baseMapper.updateById(borrower);

        // 通过借款人的userId 获取到用户信息 设置借款人状态 和 总积分的计算
        Long userId = borrower.getUserId();
        UserInfo userInfo = userInfoMapper.selectById(userId);
        userInfo.setBorrowAuthStatus(borrowerApprovalVO.getStatus());
        Integer integral = userInfo.getIntegral();

        // 计算借款人的积分 并存入到数据库
        UserIntegral userIntegral = new UserIntegral();
        userIntegral.setUserId(userId);
        userIntegral.setIntegral(borrowerApprovalVO.getInfoIntegral());
        userIntegral.setContent("借款人基本信息");
        userIntegralMapper.insert(userIntegral);
        Integer curInteger = integral + borrowerApprovalVO.getInfoIntegral();

        if (borrowerApprovalVO.getIsCarOk()) {
            userIntegral = new UserIntegral();
            userIntegral.setUserId(userId);
            userIntegral.setIntegral(IntegralEnum.BORROWER_CAR.getIntegral());
            userIntegral.setContent(IntegralEnum.BORROWER_CAR.getMsg());
            userIntegralMapper.insert(userIntegral);
            curInteger += IntegralEnum.BORROWER_CAR.getIntegral();
        }

        if (borrowerApprovalVO.getIsHouseOk()) {
            userIntegral = new UserIntegral();
            userIntegral.setUserId(userId);
            userIntegral.setIntegral(IntegralEnum.BORROWER_HOUSE.getIntegral());
            userIntegral.setContent(IntegralEnum.BORROWER_HOUSE.getMsg());
            userIntegralMapper.insert(userIntegral);
            curInteger += IntegralEnum.BORROWER_HOUSE.getIntegral();
        }

        if (borrowerApprovalVO.getIsIdCardOk()) {
            userIntegral = new UserIntegral();
            userIntegral.setUserId(userId);
            userIntegral.setIntegral(IntegralEnum.BORROWER_IDCARD.getIntegral());
            userIntegral.setContent(IntegralEnum.BORROWER_IDCARD.getMsg());
            userIntegralMapper.insert(userIntegral);
            curInteger += IntegralEnum.BORROWER_IDCARD.getIntegral();
        }
        // 更新总积分信息 和 状态信息
        userInfo.setIntegral(curInteger);
        userInfoMapper.updateById(userInfo);
    }
}
